//获取权限方法
var userInfo = getAuthority();
var powerlist = JSON.parse(userInfo).permissions;
/*自定义函数判断权限*/
template.defaults.imports.hasPower = function(data){
    if(powerlist.includes(data)){
        return true;
    }
    return false;
};

layui.use(['layer', 'form', 'table', 'util', 'dtree'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var admin = layui.admin;
    var table = layui.table;
    var util = layui.util;
    var dtree = layui.dtree;
    var Authorization = '';

    var selectedCatalog = {};//原点区划配置版本
    var addRegion={//新增区划参数
        originCode:'',//原点行政区划代码
        parentRegion:''//上级区划代码
    }
    var setting={//树设置
        regionSetting:{//区划树设置
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onExpand: onExpandRegionTree,
                onClick: zTreeRegionOnClick
            },
            view: {
                showIcon: true,
                showLine: true
            }
        }
    }

    if(userInfo){
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;

        getOrgionRegionPower();
        getCatalogData();
        initRegionTree();
    }

    // 添加
    $('#add-btn-orgionRegion').click(function () {
        showRegionAddModle();
    });

    // 编辑
    $('#edit-btn-orgionRegion').click(function () {
        //返回第一个被选中的行或如果没有选中的行则返回null。
        selectRegionRowObj = $('#regionManageTreeTable').datagrid('getSelected');
        if(selectRegionRowObj!=null){
            showRegionEditModle(selectRegionRowObj);
        }else{
            layer.msg('请先选中区划', {icon: 2});
        }
    });

    // 删除
    $('#delete-btn-orgionRegion').click(function () {
        //返回第一个被选中的行或如果没有选中的行则返回null。
        selectRegionRowObj = $('#regionManageTreeTable').datagrid('getSelected');
        if(selectRegionRowObj!=null){
            showRegionDeleteModle(selectRegionRowObj);
        }else{
            layer.msg('请先选中区划', {icon: 2});
        }
    });

    $('#import-btn-orgionRegion').click(function () {
        openImportRegionModel();
    });

    function getOrgionRegionPower() {
        var str = template("orgionRegion-tmpl",{});
        document.getElementById("orgionRegion-tmpl-box").innerHTML = str;
    }

    /*获取区划配置列表*/
    function getCatalogData(){
        var req={
            current: 1,
            size: 100,
            flag:1
        };
        axios.get(regionUrl.catalog.catalogList,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    selectedCatalog = response.data.data.records[0];
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    function initRegionTree(){
            getRegionTree('',function(data){
            renderTreeTable(data);
        })
    }

    function getRegionTree(parcode,callback){
        var req={
            regionCode : parcode,
        };
        axios.get(regionUrl.origion.queryOrigion,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    for(var i in data){
                        data[i].children=[{}];
                        data[i].isParent = true;
                        data[i].state = "closed";
                    }
                    callback(data);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    //渲染树表格
    function renderTreeTable(data) {
        $('#regionManageTreeTable').treegrid({
            idField:'id',
            treeField:'name',
            loadFilter: lasyLoadTreeTable,
            data:data,
            columns:[[
                {field:'name',title:'名称',width:200},
                {field:'parCodeName',title:'上级区划    ',width:150},
                {field:'begin',title:'X坐标',width:80},
                {field:'end',title:'Y坐标',width:80},
                {field:'regionCodeType',title:'行政区域类型',width:200,formatter: function(value,row,index){
                    switch (row.regionCodeType){
                        case 1:
                            return "普通区划";
                            break;
                        case 2:
                            return "高新区";
                            break;
                        case 3:
                            return "特色区划";
                            break;
                        default:
                            break;
                    }
                }},
                {field:'memo',title:'描述',width:250}
            ]]
        });
    }

    //树表格
    function lasyLoadTreeTable(data,parentId){
        function setData(data){
            var todo = [];
            for(var i=0; i<data.length; i++){
                todo.push(data[i]);
            }
            while(todo.length){
                var node = todo.shift();
                if (node.children && node.children.length){
                    node.state = 'closed';
                    node.children1 = node.children;
                    node.children = [];
                    todo = todo.concat(node.children1);
                }
            }

            return data;
        }
        setData(data);
        var tg = $(this);
        var opts = tg.treegrid('options');

        opts.onBeforeExpand = function(row) {
            if (row.children.length<1) {
                getRegionTree(row.code, function (newRegionCata) {
                    tg.treegrid('append', {
                        parent: row[opts.idField],
                        data: newRegionCata
                    });

                    row.children1 = undefined;
                    tg.treegrid('expand', row[opts.idField]);

                })
            };
            return row.children1 == undefined;
        }
        return data;

    }

    // 添加弹窗
    function showRegionAddModle() {
        admin.open({
            type: 1,
            title: '新增行政区划',
            area: ['350px', '480px'],
            offset:'auto',
            content: $('#addRegionManage').html(),
            success: function (layero, dIndex) {
                addRegion.originCode = '';
                addRegion.parentRegion = '';
                lazyLoadRegionTree();
                $("#parentRegionName").click(function () {
                    $("#RegionTree").css('display','block');
                })

                form.render('select'); //刷新select选择框渲染
                form.on('submit(regionEditSubmit)', function (data) {
                    var req = data.field;
                    if(addRegion.parentRegion==null||addRegion.parentRegion==""){
                        layer.msg('请设置上级区划', {icon: 2});
                        return false;
                    }
                    req.flag = 1;
                    req.originCode = addRegion.originCode;
                    req.rcid = selectedCatalog.id;
                    req.parCode = addRegion.parentRegion;

                    axios({
                        method: 'POST',
                        url:regionUrl.info.addRegion,
                        data:$.param(req),
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (response) {
                            if(response.status == 200 &&response.data.message == "success"){
                                layer.close(dIndex);
                                layer.closeAll('loading');
                                layer.msg(response.data.message, {icon: 1});
                                initRegionTree();
                            }else{
                                layer.closeAll('loading');
                                layer.msg(response.data.message, {icon: 2});
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                            if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                // 进行重新登陆
                                localStorage.clear();
                                top.location.href=loginPageUrl;
                            }
                        });
                    return false;
                });
            }
        });
    }
    //编辑弹窗
    function showRegionEditModle(selectedRegion) {
        if(selectedRegion.code!="000000000000"){
            admin.open({
                type: 1,
                title: '编辑行政区划',
                area: ['350px', '480px'],
                offset:'auto',
                content: $('#addRegionManage').html(),
                success: function (layero, dIndex) {
                    addRegion.originCode = '';
                    // addRegion.parentRegion = '';
                    $("#parentRegionName").text(selectedRegion.parCodeName);
                    addRegion.parentRegion = selectedRegion.parCode;
                    lazyLoadRegionTree();
                    $("#parentRegionName").click(function () {
                        $("#RegionTree").css('display','block');
                    })

                    form.render('select'); //刷新select选择框渲染
                    form.val('regionForm',selectedRegion);

                    form.on('submit(regionEditSubmit)', function (data) {
                        var req = data.field;
                        if(addRegion.parentRegion==null||addRegion.parentRegion==""){
                            layer.msg('请设置上级区划', {icon: 2});
                            return false;
                        }
                        req.flag = 1;
                        req.rcid = selectedCatalog.id;
                        req.parCode = addRegion.parentRegion;
                        req.id = selectedRegion.id;
                        req.version = selectedRegion.version;

                        axios({
                            method: 'PUT',
                            url:regionUrl.info.editRegion,
                            data:$.param(req),
                            headers:{
                                'Authorization':Authorization
                            }
                        })
                            .then(function (response) {
                                if(response.status == 200 &&response.data.message == "success"){
                                    layer.close(dIndex);
                                    layer.closeAll('loading');
                                    layer.msg(response.data.message, {icon: 1});
                                    initRegionTree();
                                }else{
                                    layer.closeAll('loading');
                                    layer.msg(response.data.message, {icon: 2});
                                }
                            })
                            .catch(function (error) {
                                console.log(error);
                                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                    // 进行重新登陆
                                    localStorage.clear();
                                    top.location.href=loginPageUrl;
                                }
                            });
                        return false;
                    });
                }
            });
        }else{
            layer.msg("全国不允许编辑", {icon: 2});
        }
    }

    // 删除区划
    function showRegionDeleteModle(selectRegionRowObj) {

        layer.confirm('确定要删除区划“' + selectRegionRowObj.name + '”吗？', {
            skin: 'layui-layer-admin',
            shade: .1,
            cancel: function(index, layero){
                layer_popup = false;//取消操作，点击右上角的X去掉弹窗限制
            }
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:regionUrl.info.deleteRegion+selectRegionRowObj.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("成功删除", {icon: 1});
                        initRegionTree();
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        });
    }

    //懒加载区划树(选择上级区划时用)
    function lazyLoadRegionTree() {
        var req={
            regionCode:""
        };
        axios.get(regionUrl.origion.queryOrigion,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var datas = response.data.data;
                    if (datas.length > 0) {
                        for (const row of datas) {
                            row.isParent = true;
                            row.sub = []; //存放子节点
                            row.drag = true;
                        }
                    }
                    $.fn.zTree.init($("#RegionTree"), setting.regionSetting, datas);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    //展开下级区划
    function onExpandRegionTree(event, treeId, treeNode){
        if(treeNode.sub.length==0){
            var req={
                regionCode: treeNode.code,
            };
            axios.get(regionUrl.origion.queryOrigion,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var datas = response.data.data;
                        if (datas.length > 0) {
                            for (const row of datas) {
                                row.isParent = true;
                                row.sub = []; //存放子节点
                                row.drag = true;
                            }
                        }
                        const treeObj = $.fn.zTree.getZTreeObj("RegionTree");
                        treeObj.addNodes(treeNode, datas);
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }
    }

    //区划选中事件
    function zTreeRegionOnClick(event, treeId, treeNode){
        $("#parentRegionName").text(treeNode.name);
        addRegion.parentRegion=treeNode.code;
        $("#RegionTree").css('display','none');
    }


    /*显示导入区划弹窗*/
    function openImportRegionModel() {
        window.importRegionIsOk = false;
        window.orgion_selectedCatalog = selectedCatalog;
        admin.open({
            title: '导入区划树',
            url: 'orgion/importRegion.html',
            end: function () {
                if(window.importRegionIsOk){
                    getCatalogData();
                    initRegionTree();
                }
            },
            success: function (layero, dIndex) {
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }
})